package com.sale.table.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.order.api.RemoteSaleService;
import com.sale.storage.api.RemoteWarehouseNameService;
import com.sale.storage.api.RemoteWarehouseReportService;
import com.sale.storage.api.dto.InvoicingReportDto;
import com.sale.storage.api.vo.InventoryBalanceVo;
import com.sale.system.api.RemoteInventoryAccountingService;
import com.sale.system.api.RemoteInventoryInquiryService;
import com.sale.system.api.RemoteUnitService;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysAuxiliaryUnitDetail;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.dto.SysAuxiliaryUnitDateDetailResultDto;
import com.sale.system.api.model.MaterialUnitDto;
import com.sale.table.domain.dto.*;
import com.sale.table.domain.vo.SaleOrderTraceVo;
import com.sale.table.domain.vo.SalesTotalVo;
import com.sale.table.mapper.SaleOrderStatisticsMapper;
import com.sale.table.service.SaleOrderStatisticsService;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售统计报表 实现层
 */
@RequiredArgsConstructor
@Service
public class SaleOrderStatisticsServiceImpl implements SaleOrderStatisticsService {

    @Resource
    SaleOrderStatisticsMapper saleOrderStatisticsMapper;

    @DubboReference
    RemoteUnitService remoteUnitService;

    @DubboReference
    RemoteWarehouseReportService remoteWarehouseReportService;

    @DubboReference
    RemoteInventoryAccountingService remoteInventoryAccountingService;

    @DubboReference
    RemoteSaleService remoteSaleService;

    @DubboReference
    RemoteWarehouseNameService remoteWarehouseNameService;

    @DubboReference
    RemoteInventoryInquiryService remoteInventoryInquiryService;

    /**
     * 销售订单跟踪 列表
     *
     * @param saleOrderTraceVo
     * @return
     */
    @Override
    public TableDataInfo<SaleOrderTraceDto> getSaleOrderTraceList(SaleOrderTraceVo saleOrderTraceVo, PageQuery pageQuery) {
        List<SaleOrderTraceDto> records = saleOrderStatisticsMapper.getSaleOrderTraceList(saleOrderTraceVo);
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sales_order_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取不同销售发货单单号及最新时间
        Map<String, Date> newSaleMap = remoteSaleService.getNewSaleMap();
        for (SaleOrderTraceDto entity : records) {
            //交货日期
            Date date = newSaleMap.get(entity.getSaleOrderNo());
            entity.setEstimatedTime(date);
            //假如已出库量大于计划量
            BigDecimal multiply = new BigDecimal("0");
            if(entity.getActualQuantity().compareTo(entity.getPlannedWeight()) > 0){
                //未开票金额 = 计划量 * 单价 - 已开票金额
                 multiply = new BigDecimal(String.valueOf(entity.getPlannedWeight())).multiply(new BigDecimal(entity.getUnitPrice()));
            }else {
                //未开票金额 = 已出库量 * 单价 - 已开票金额
                 multiply = new BigDecimal(String.valueOf(entity.getActualQuantity())).multiply(new BigDecimal(entity.getUnitPrice()));
            }
            BigDecimal subtract = multiply.subtract(entity.getInvoicedAmount());
            entity.setNoInvoicedAmount(subtract);
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
            entity.setAuxiliaryAttribute(statsArray);
            //单位
            if (entity.getMaterialUnit() != null) {
                entity.setUnitDict(remoteUnitService.getUnitDataByCode(Long.parseLong(entity.getMaterialUnit())).getData().getUnitName());
            }
            //销售订单状态
            entity.setStatusDict(statusMap.get(entity.getStatus()));
        }
        //手动分页
        Page<SaleOrderTraceDto> page = new Page<>();
        List<SaleOrderTraceDto> collect = records.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
        page.setRecords(collect);
        page.setTotal(records.size());
        return TableDataInfo.build(page);
    }

    /**
     * 销售收款一览表列表
     */
    @Override
    public TableDataInfo<SalesCollectionDto> getSalesCollectionList(SaleOrderTraceVo saleOrderTraceVo, PageQuery pageQuery) {
        List<SalesCollectionDto> resultList = new ArrayList<>();
        //销售发货数据
        List<SalesCollectionDto> pickingSaleList = saleOrderStatisticsMapper.getSalesCollectionList(saleOrderTraceVo);
        //销售退货数据
        List<SalesCollectionDto> salesReturnList = saleOrderStatisticsMapper.getSalesReturnList(saleOrderTraceVo);
        resultList.addAll(pickingSaleList);
        resultList.addAll(salesReturnList);
        Page<SalesCollectionDto> page = new Page<>();
        List<SalesCollectionDto> collect = resultList.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
        page.setRecords(collect);
        page.setTotal(resultList.size());
        return TableDataInfo.build(page);
    }

    /**
     * 销售汇总表
     */
    @Override
    public TableDataInfo<SalesTotalDto> getSalesTotalList(SalesTotalVo salesTotalVo, PageQuery pageQuery) throws Exception {
        InventoryBalanceVo inventoryBalanceVo = new InventoryBalanceVo();
        List<InvoicingReportDto> invoicingReport = remoteWarehouseReportService.getInvoicingReport(inventoryBalanceVo);
        //根据物料编码转为map
//        Map<String, String> invoicingReportMap = invoicingReport.stream()
//            .filter(entity -> entity.getWodDocNum() != null && entity.getBalancePrice() != null && entity.getType() == 1)
//            .collect(Collectors.toMap(InvoicingReportDto::getWodDocNum, InvoicingReportDto::getBalancePrice));
        Map<String, List<InvoicingReportDto>> invoicingReportMap = invoicingReport.stream()
            .filter(entity -> entity.getType() != 1)
            .collect(Collectors.groupingBy(InvoicingReportDto::getMaterialCode));

        //获取物料多单位map集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();

        //多单位转换map
        Map<Long, String> unitToMap = remoteUnitService.getUnitToMap();

        if (salesTotalVo.getStatisticalMethod() == 1) {
            if(salesTotalVo.getSupplierName() != null){
                String warehouseName = remoteWarehouseNameService.getCombinationByWarehouseId(Long.parseLong(salesTotalVo.getSupplierName()));
                salesTotalVo.setWarehouseName(warehouseName);
            }
            //物料统计
            List<SalesTotalDto> salesTotalList = saleOrderStatisticsMapper.getSalesTotalList(salesTotalVo);

            //排除掉没有入库的数据
            List<SalesTotalDto> collect1 = salesTotalList.stream().filter(entity -> entity.getWarehouseDict() != null).collect(Collectors.toList());
            //根据物料编码和仓库名称进行分组
            Map<String, Map<String, List<SalesTotalDto>>> infoMap = collect1.stream()
                .collect(Collectors.groupingBy(SalesTotalDto::getMaterialCode, Collectors.groupingBy(x -> Optional.ofNullable(x.getWarehouseDict()).orElse("0"))));

            List<SalesTotalDto> objects = new ArrayList<>();
            for (Map.Entry<String, Map<String, List<SalesTotalDto>>> entry : infoMap.entrySet()) {

                Map<String, List<SalesTotalDto>> value = entry.getValue();
                for (Map.Entry<String, List<SalesTotalDto>> value1 : value.entrySet()) {
                    SalesTotalDto salesTotalDto = new SalesTotalDto();
                    //物料编码
                    salesTotalDto.setMaterialCode(entry.getKey());
                    List<SalesTotalDto> value2 = value1.getValue();
                    //辅助属性
                    List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + value2.get(0).getTenantId(), String.valueOf(value2.get(0).getMaterialId()));
                    salesTotalDto.setAuxiliaryAttribute(statsArray);
                    //类别
                    if ("1".equals(value2.get(0).getCategory())) {
                        salesTotalDto.setCategoryDict("原料");
                    } else {
                        salesTotalDto.setCategoryDict("成品");
                    }
                    //物料名称
                    salesTotalDto.setMaterialName(value2.get(0).getMaterialName());
                    //物料类别
                    salesTotalDto.setMaterialCategory(value2.get(0).getMaterialCategory());
                    //规格
                    salesTotalDto.setMaterialSpec(value2.get(0).getMaterialSpec());
                    //仓库
                    salesTotalDto.setWarehouseDict(value2.get(0).getWarehouseDict());

                    MaterialUnitDto unitByCode = unitByCodeToMap.get(entry.getKey());

                    //获取单价之和
                    BigDecimal bigDecimal = new BigDecimal("0");
                    //获取单位数量之和
                    BigDecimal bigDecimal1 = new BigDecimal("0");
                    for (SalesTotalDto entity : value2) {
                        if (entity.getUnitPrice() != null) {
                            bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(entity.getUnitPrice())));
                        }

                        if (entity.getActualNumber() != null) {
                            bigDecimal1 = bigDecimal1.add(new BigDecimal(String.valueOf(entity.getActualNumber())));
                        }
                    }
                    //多单位转换获取单位数量
                    Long unit = value2.get(0).getUnit();
                    String convertUnit = unitToMap.get(unit);
                    BigDecimal multiplyUnit = new BigDecimal("0");
                    if(convertUnit != null){
                        multiplyUnit = bigDecimal1.multiply(new BigDecimal(convertUnit));
                    }else {
                        multiplyUnit = bigDecimal1;
                    }
                    //单位数量
                    salesTotalDto.setMaterialTotal(multiplyUnit.toString());
                    if(value2.get(0).getMaterialMoreUnit() != null){
                        SysAuxiliaryUnitDateDetailResultDto materialUnitById = remoteInventoryInquiryService.getMaterialUnitById(Long.valueOf(value2.get(0).getMaterialUnit()),value2.get(0).getMaterialId());

                        // 获取逗号前的基础单位
                        int str = materialUnitById.getAuxiliaryUnitName().indexOf(',');
                        String substring = materialUnitById.getAuxiliaryUnitName().substring(0, str);
                        long c = (long)(Double.parseDouble(String.valueOf(multiplyUnit)));
                        MaterialUnitDto materialUnitDto = remoteInventoryInquiryService.selectMaterialUnitList(Long.valueOf(value2.get(0).getMaterialMoreUnit()), c);
                        //多单位
                        salesTotalDto.setMaterialMoreUnit(materialUnitById.getAuxiliaryUnitName());

                        //多单位数量
                        salesTotalDto.setMaterialMoreUnitNumber(materialUnitDto.getUnitName());
                        //单位
                        salesTotalDto.setUnitDict(substring);
                    }else {
                        //单位
                        salesTotalDto.setUnitDict(unitByCode.getUnitName());
                    }


                    //销售成本 = 单位数量*结存单价；(结存单价从进销存统计表中获取)
                    List<InvoicingReportDto> invoicingReportDtos = invoicingReportMap.get(value2.get(0).getMaterialCode());
                    InvoicingReportDto invoicingReportDto = invoicingReportDtos.get(invoicingReportDtos.size() -1);
                    String s = invoicingReportDto.getBalancePrice();
//                    String s = null;
                    String valueCost;
                    if (s == null || "0".equals(s)) {
                        valueCost = "0";
                    } else {
                        valueCost = s;
                    }
                    BigDecimal multiply = multiplyUnit.multiply(new BigDecimal(valueCost));
                    salesTotalDto.setSaleCost(multiply);
                    //销售毛利=销售金额-销售成本
                    BigDecimal subtract1 = bigDecimal.multiply(multiplyUnit);
                    //销售金额
                    salesTotalDto.setSaleAmount(subtract1);
                    BigDecimal subtract = subtract1.subtract(new BigDecimal(valueCost));
                    salesTotalDto.setSaleGrossProfit(subtract);
                    //单价
                    if(multiplyUnit.compareTo(BigDecimal.ZERO) != 0){
                        salesTotalDto.setUnitPrice(subtract1.divide(multiplyUnit,2));
                    }
                    //销售毛利率=销售毛利/销售金额
                    if(subtract1.compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal divide = subtract.divide(subtract1, 2);
                        BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                        salesTotalDto.setGrossProfitMargin(multiply1 + "%");
                    }

                    objects.add(salesTotalDto);
                }
            }
            //手动分页
            Page<SalesTotalDto> page = new Page<>();
            List<SalesTotalDto> collect = objects.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
            page.setRecords(collect);
            page.setTotal(objects.size());
            return TableDataInfo.build(page);
//            for (SalesTotalDto entity : records) {
//                //辅助属性
//                List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
//                entity.setAuxiliaryAttribute(statsArray);
//                //类别
//                if ("1".equals(entity.getCategory())) {
//                    entity.setCategoryDict("原料");
//                } else {
//                    entity.setCategoryDict("成品");
//                }
//                MaterialUnitDto unitByCode = remoteUnitService.getUnitByCode(entity.getMaterialCode());
//                //多单位
//                entity.setMaterialMoreUnit(unitByCode.getAuxiliaryUnit());
//                //多单位数量
//                entity.setMaterialMoreUnitNumber(getMoreUnit(String.valueOf(entity.getMaterialTotal()), unitByCode));
//                //单位
//                entity.setUnitDict(unitByCode.getUnitName());
//                //销售成本 = 单位数量*结存单价；(结存单价从进销存统计表中获取)
//                String s = invoicingReportMap.get(entity.getDocumentNumber());
//                String value;
//                if (s == null) {
//                    value = "0";
//                } else {
//                    value = s;
//                }
//                BigDecimal multiply = new BigDecimal(entity.getMaterialTotal()).multiply(new BigDecimal(value));
//                entity.setSaleCost(multiply);
//                //销售毛利=销售金额-销售成本
//                BigDecimal subtract = entity.getSaleAmount().subtract(new BigDecimal(value));
//                entity.setSaleGrossProfit(subtract);
//                //销售毛利率=销售毛利/销售金额
//                if(entity.getSaleAmount().compareTo(BigDecimal.ZERO) != 0){
//                    BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
//                    BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
//                    entity.setGrossProfitMargin(multiply1 + "%");
//                }
//            }
        } else {
            //客户统计
            List<SalesTotalDto> records = saleOrderStatisticsMapper.getSalesTotalCustomerList(salesTotalVo);
            //根据供应商编码、物料编码、仓库名称进行分组
            Map<String, Map<String, Map<String, List<SalesTotalDto>>>> styleMap = records.stream()
                .collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getCustomerCode()).orElse("0"),
                    Collectors.groupingBy(SalesTotalDto::getMaterialCode,
                        Collectors.groupingBy(x -> Optional.ofNullable(x.getWarehouseDict()).orElse("0")))));

            List<SalesTotalDto> objects = new ArrayList<>();
            for (Map.Entry<String, Map<String, Map<String, List<SalesTotalDto>>>> entry : styleMap.entrySet()) {
                Map<String, Map<String, List<SalesTotalDto>>> value = entry.getValue();

                for (Map.Entry<String, Map<String, List<SalesTotalDto>>> entry1 : value.entrySet()) {
                    Map<String, List<SalesTotalDto>> value1 = entry1.getValue();
                    for (Map.Entry<String, List<SalesTotalDto>> value2 : value1.entrySet()) {
                        SalesTotalDto salesTotalDto = new SalesTotalDto();

                        //物料编码
                        salesTotalDto.setMaterialCode(entry1.getKey());

                        //仓库
                        salesTotalDto.setWarehouseDict(value2.getKey());
                        List<SalesTotalDto> value3 = value2.getValue();
                        //辅助属性
                        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + value3.get(0).getTenantId(), String.valueOf(value3.get(0).getMaterialId()));
                        salesTotalDto.setAuxiliaryAttribute(statsArray);

                        //物料名称
                        salesTotalDto.setMaterialName(value3.get(0).getMaterialName());
                        //物料类别
                        salesTotalDto.setMaterialCategory(value3.get(0).getMaterialCategory());
                        //规格
                        salesTotalDto.setMaterialSpec(value3.get(0).getMaterialSpec());
                        //仓库
                        salesTotalDto.setWarehouseDict(value3.get(0).getWarehouseDict());
                        //类别
                        if ("1".equals(value3.get(0).getCategory())) {
                            salesTotalDto.setCategoryDict("原料");
                        } else {
                            salesTotalDto.setCategoryDict("成品");
                        }
                        MaterialUnitDto unitByCode = unitByCodeToMap.get(entry1.getKey());

                        //获取单价之和
                        BigDecimal bigDecimal = new BigDecimal("0");
                        //获取单位数量之和
                        BigDecimal bigDecimal1 = new BigDecimal("0");
                        for (SalesTotalDto entity : value3) {
                            if (entity.getUnitPrice() != null) {
                                bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(entity.getUnitPrice())));
                            }

                            if (entity.getActualNumber() != null) {
                                bigDecimal1 = bigDecimal1.add(new BigDecimal(String.valueOf(entity.getActualNumber())));
                            }
                        }
                        //多单位转换获取单位数量
                        Long unit = value3.get(0).getUnit();
                        String convertUnit = unitToMap.get(unit);
                        BigDecimal multiplyUnit = new BigDecimal("0");
                        if(convertUnit != null){
                            multiplyUnit = bigDecimal1.multiply(new BigDecimal(convertUnit));
                        }else {
                            multiplyUnit = bigDecimal1;
                        }

                        //单位数量
                        salesTotalDto.setMaterialTotal(multiplyUnit.toString());

                        if(value3.get(0).getMaterialMoreUnit() != null){
                            SysAuxiliaryUnitDateDetailResultDto materialUnitById = remoteInventoryInquiryService.getMaterialUnitById(Long.valueOf(value3.get(0).getMaterialUnit()),value3.get(0).getMaterialId());
                            // 多计量单位名称

                            // 获取逗号前的基础单位
                            int str = materialUnitById.getAuxiliaryUnitName().indexOf(',');
                            String substring = materialUnitById.getAuxiliaryUnitName().substring(0, str);
                            long c = (long)(Double.parseDouble(String.valueOf(multiplyUnit)));
                            MaterialUnitDto materialUnitDto = remoteInventoryInquiryService.selectMaterialUnitList(Long.valueOf(value3.get(0).getMaterialMoreUnit()), c);
                            //多单位
                            salesTotalDto.setMaterialMoreUnit(materialUnitById.getAuxiliaryUnitName());

                            //多单位数量
                            salesTotalDto.setMaterialMoreUnitNumber(materialUnitDto.getUnitName());
                            //单位
                            salesTotalDto.setUnitDict(substring);
                        }else {
                            //单位
                            salesTotalDto.setUnitDict(unitByCode.getUnitName());
                        }

                        //销售成本 = 单位数量*结存单价；(结存单价从进销存统计表中获取)
//                    String s = invoicingReportMap.get(value3.get(0).getDocumentNumber());
                        List<InvoicingReportDto> invoicingReportDtos = invoicingReportMap.get(value3.get(0).getMaterialCode());
                        InvoicingReportDto invoicingReportDto = invoicingReportDtos.get(invoicingReportDtos.size() -1);
                        String s = invoicingReportDto.getBalancePrice();
//                        String s = null;
                        String valueCost;
                        if (s == null || "0".equals(s)) {
                            valueCost = "0";
                        } else {
                            valueCost = s;
                        }
                        BigDecimal multiply = multiplyUnit.multiply(new BigDecimal(valueCost));
                        salesTotalDto.setSaleCost(multiply);
                        //销售毛利=销售金额-销售成本
                        BigDecimal subtract1 = bigDecimal.multiply(multiplyUnit);
                        //销售金额
                        salesTotalDto.setSaleAmount(subtract1);
                        BigDecimal subtract = subtract1.subtract(new BigDecimal(valueCost));
                        salesTotalDto.setSaleGrossProfit(subtract);
                        //单价
                        if(multiplyUnit.compareTo(BigDecimal.ZERO) != 0){
                            salesTotalDto.setUnitPrice(subtract1.divide(multiplyUnit,2));
                        }
                        //销售毛利率=销售毛利/销售金额
                        if(subtract1.compareTo(BigDecimal.ZERO) != 0){
                            BigDecimal divide = subtract.divide(subtract1, 2);
                            BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                            salesTotalDto.setGrossProfitMargin(multiply1 + "%");
                        }
                        //供应商编码
                        salesTotalDto.setCustomerCode(value3.get(0).getCustomerCode());
                        //供应商名称
                        salesTotalDto.setCustomerName(value3.get(0).getCustomerName());
                        objects.add(salesTotalDto);
                    }
//            for (SalesTotalDto entity : records) {
//                //辅助属性
//                List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
//                entity.setAuxiliaryAttribute(statsArray);
//                //类别
//                if ("1".equals(entity.getCategory())) {
//                    entity.setCategoryDict("原料");
//                } else {
//                    entity.setCategoryDict("成品");
//                }
//                MaterialUnitDto unitByCode = remoteUnitService.getUnitByCode(entity.getMaterialCode());
//                //多单位
//                entity.setMaterialMoreUnit(unitByCode.getAuxiliaryUnit());
//                //多单位数量
//                entity.setMaterialMoreUnitNumber(getMoreUnit(String.valueOf(entity.getMaterialTotal()), unitByCode));
//                //单位
//                entity.setUnitDict(unitByCode.getUnitName());
//                //销售成本 = 单位数量*结存单价；(结存单价从进销存统计表中获取)
//                String s = invoicingReportMap.get(entity.getDocumentNumber());
//
//                String value;
//                if (s == null) {
//                    value = "0";
//                } else {
//                    value = s;
//                }
//
//                BigDecimal multiply = new BigDecimal(entity.getMaterialTotal()).multiply(new BigDecimal(value));
//                entity.setSaleCost(multiply);
//                //销售毛利=销售金额-销售成本
//                BigDecimal subtract = entity.getSaleAmount().subtract(new BigDecimal(value));
//                entity.setSaleGrossProfit(subtract);
//                //销售毛利率=销售毛利/销售金额
//                if(entity.getSaleAmount().compareTo(BigDecimal.ZERO) != 0){
//                    BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
//                    BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
//                    entity.setGrossProfitMargin(multiply1 + "%");
//                }
//            }
                }
            }
            //手动分页
            Page<SalesTotalDto> page = new Page<>();
            List<SalesTotalDto> collect = objects.stream().skip((long) (pageQuery.getPageNum() - 1) * pageQuery.getPageSize()).limit(pageQuery.getPageSize()).collect(Collectors.toList());
            page.setRecords(collect);
            page.setTotal(objects.size());
            return TableDataInfo.build(page);
        }
    }
    /**
     * 销售排行表
     */
    @Override
    public TableDataInfo<SalesRankingDto> salesRankingList(SalesTotalVo salesTotalVo, PageQuery pageQuery) throws Exception {
        //获取进销存统计表数据
        InventoryBalanceVo inventoryBalanceVo = new InventoryBalanceVo();
        List<InvoicingReportDto> invoicingReport = remoteWarehouseReportService.getInvoicingReport(inventoryBalanceVo);
        //根据单据号转为map(加权平均使用)
//        Map<String, List<InvoicingReportDto>> invoicingReportMap = invoicingReport.stream()
//            .filter(entity -> entity.getType() != 1)
//            .collect(Collectors.groupingBy(InvoicingReportDto::getMaterialCode));
        PageQuery pageQuery1 = new PageQuery();
        pageQuery1.setPageNum(1);
        pageQuery1.setPageSize(10);
        //获取销售汇总表数据
        TableDataInfo<SalesTotalDto> salesTotalList = getSalesTotalList(salesTotalVo, pageQuery1);
        List<SalesTotalDto> rows = salesTotalList.getRows();
        //根据单据号转为map(先进先出使用)
//        Map<String, BigDecimal> collect = rows.stream().filter(entity -> entity.getDocumentNumber() == null && !"0".equals(entity.getMaterialTotal()))
//            .collect(Collectors.toMap(SalesTotalDto::getMaterialCode,
//                entity -> entity.getSaleCost().divide(new BigDecimal(String.valueOf(entity.getMaterialTotal())),2)));
        List<SalesTotalDto> collect = rows.stream().filter(entity -> entity.getDocumentNumber() == null && !"0".equals(entity.getMaterialTotal())).collect(Collectors.toList());

        //判断是先进先出还是加权平均
        int type = remoteInventoryAccountingService.getCostAccountingMethod();


        if (salesTotalVo.getStatisticalMethod() == 1) {
            //物料统计
            Page<SalesRankingDto> salesRankingMaterialList = saleOrderStatisticsMapper.getSalesRankingMaterialList(salesTotalVo, pageQuery.build());
            List<SalesRankingDto> records = salesRankingMaterialList.getRecords();
            for (SalesRankingDto entity : records) {
                //辅助属性
                List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
                entity.setAuxiliaryAttribute(statsArray);
                //类别
                if (entity.getCategory() == 1) {
                    entity.setCategoryDict("原料");
                } else {
                    entity.setCategoryDict("成品");
                }
                if (type == 1) {
                    //加权平均
//                    String s = invoicingReportMap.get(entity.getMaterialCode());
//                    List<InvoicingReportDto> invoicingReportDtos = invoicingReportMap.get(entity.getMaterialCode());
//                    InvoicingReportDto invoicingReportDto = invoicingReportDtos.get(invoicingReportDtos.size() -1);
//                    String s = invoicingReportDto.getBalanceAmount();
//                    BigDecimal bigDecimal = collect.get(entity.getMaterialCode());
                    BigDecimal bigDecimal = new BigDecimal("0");
                    for(SalesTotalDto entityCollect : collect){
                        if(entity.getMaterialCode().equals(entityCollect.getMaterialCode()) && entity.getWarehouseDict().equals(entityCollect.getWarehouseDict())){
                            bigDecimal = entityCollect.getSaleCost().divide(new BigDecimal(String.valueOf(entityCollect.getMaterialTotal())), 2);
                        }
                    }
                    if (bigDecimal != null) {
                        //单位成本(【加权平均法】：等于【进销存统计表】中的结存成本)
                        entity.setUnitCost(bigDecimal.toString());
                        //销售成本=销售数量*单位成本
                        BigDecimal multiply = new BigDecimal(entity.getSalesVolume()).multiply(bigDecimal);
                        entity.setSaleCost(multiply);
                        //销售毛利=销售金额-销售成本
                        BigDecimal subtract = entity.getSaleAmount().subtract(multiply);
                        entity.setSaleGrossProfit(subtract);
                        //销售毛利率=销售毛利/销售金额*100%
                        BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
                        BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                        entity.setGrossProfitMargin(multiply1 + "%");
                    }
                } else {
                    //先进先出
//                    BigDecimal bigDecimal = collect.get(entity.getMaterialCode());
                    BigDecimal bigDecimal = new BigDecimal("0");
                    for(SalesTotalDto entityCollect : collect){
                        if(entity.getMaterialCode().equals(entityCollect.getMaterialCode()) && entity.getWarehouseDict().equals(entityCollect.getWarehouseDict())){
                            bigDecimal = entityCollect.getSaleCost().divide(new BigDecimal(String.valueOf(entityCollect.getMaterialTotal())), 2);
                        }
                    }
                    //销售排行榜单位成本=销售汇总表销售成本/单位数量
                    if (bigDecimal != null) {
                        //单位成本
                        entity.setUnitCost(bigDecimal.toString());
                        //销售成本=销售数量*单位成本
                        BigDecimal multiply = new BigDecimal(entity.getSalesVolume()).multiply(bigDecimal);
                        entity.setSaleCost(multiply);
                        //销售毛利=销售金额-销售成本
                        BigDecimal subtract = entity.getSaleAmount().subtract(multiply);
                        entity.setSaleGrossProfit(subtract);
                        //销售毛利率=销售毛利/销售金额*100%
                        BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
                        BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                        entity.setGrossProfitMargin(multiply1 + "%");
                    }
                }
            }
            return TableDataInfo.build(salesRankingMaterialList);
        } else {
            //客户统计
            String userIdStr = LoginHelper.getUserIdStr();
            String tenantId = RedisUtils.getCacheObject(userIdStr);
            salesTotalVo.setTenantId(tenantId);
            Page<SalesRankingDto> salesRankingCustomerList = saleOrderStatisticsMapper.getSalesRankingCustomerList(salesTotalVo, pageQuery.build());
            List<SalesRankingDto> records = salesRankingCustomerList.getRecords();
            for (SalesRankingDto entity : records) {
                //辅助属性
                List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + entity.getTenantId(), String.valueOf(entity.getMaterialId()));
                entity.setAuxiliaryAttribute(statsArray);
                //类别
                if (entity.getCategory() == 1) {
                    entity.setCategoryDict("原料");
                } else {
                    entity.setCategoryDict("成品");
                }
                if (type == 1) {
                    //加权平均
//                    String s = invoicingReportMap.get(entity.getDocumentNumber());
//                    List<InvoicingReportDto> invoicingReportDtos = invoicingReportMap.get(entity.getMaterialCode());
//                    InvoicingReportDto invoicingReportDto = invoicingReportDtos.get(invoicingReportDtos.size() -1);
//                    String s = invoicingReportDto.getBalanceAmount();
//                    BigDecimal bigDecimal = collect.get(entity.getMaterialCode());
                    BigDecimal bigDecimal = new BigDecimal("0");
                    for(SalesTotalDto entityCollect : collect){
                        if(entity.getMaterialCode().equals(entityCollect.getMaterialCode()) && entity.getWarehouseDict().equals(entityCollect.getWarehouseDict())){
                            bigDecimal = entityCollect.getSaleCost().divide(new BigDecimal(String.valueOf(entityCollect.getMaterialTotal())), 2);
                        }
                    }
                    if (bigDecimal != null) {
                        //单位成本(【加权平均法】：等于【进销存统计表】中的结存成本)
                        entity.setUnitCost(bigDecimal.toString());
                        //销售成本=销售数量*单位成本
                        BigDecimal multiply = new BigDecimal(entity.getSalesVolume()).multiply(bigDecimal);
                        entity.setSaleCost(multiply);
                        //销售毛利=销售金额-销售成本
                        BigDecimal subtract = entity.getSaleAmount().subtract(multiply);
                        entity.setSaleGrossProfit(subtract);
                        //销售毛利率=销售毛利/销售金额*100%
                        BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
                        BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                        entity.setGrossProfitMargin(multiply1 + "%");
                    }
                } else {
                    //先进先出
//                    BigDecimal bigDecimal = collect.get(entity.getMaterialCode());
                    BigDecimal bigDecimal = new BigDecimal("0");
                    for(SalesTotalDto entityCollect : collect){
                        if(entity.getMaterialCode().equals(entityCollect.getMaterialCode()) && entity.getWarehouseDict().equals(entityCollect.getWarehouseDict())){
                            bigDecimal = entityCollect.getSaleCost().divide(new BigDecimal(String.valueOf(entityCollect.getMaterialTotal())), 2);
                        }
                    }
                    //销售排行榜单位成本=销售汇总表销售成本/单位数量
                    if (bigDecimal != null) {
                        //单位成本
                        entity.setUnitCost(bigDecimal.toString());
                        //销售成本=销售数量*单位成本
                        BigDecimal multiply = new BigDecimal(entity.getSalesVolume()).multiply(bigDecimal);
                        entity.setSaleCost(multiply);
                        //销售毛利=销售金额-销售成本
                        BigDecimal subtract = entity.getSaleAmount().subtract(multiply);
                        entity.setSaleGrossProfit(subtract);
                        //销售毛利率=销售毛利/销售金额*100%
                        BigDecimal divide = subtract.divide(entity.getSaleAmount(), 2);
                        BigDecimal multiply1 = divide.multiply(new BigDecimal("100"));
                        entity.setGrossProfitMargin(multiply1 + "%");
                    }
                }
            }
            return TableDataInfo.build(salesRankingCustomerList);
        }
    }

    /**
     * 获取多单位数量
     *
     * @param materialTotal
     * @param unitByCode
     * @return
     */
    public String getMoreUnit(String materialTotal, MaterialUnitDto unitByCode) {
        String moreUnit = "";

        String num = materialTotal;

        List<SysAuxiliaryUnitDetail> list = unitByCode.getList();
        if (list != null) {
            for (SysAuxiliaryUnitDetail sysAuxiliaryUnitDetail : list) {
                String unitQuantity = sysAuxiliaryUnitDetail.getUnitQuantity();
                BigDecimal number1 = new BigDecimal(num);
                BigDecimal number2 = new BigDecimal(unitQuantity);
                BigDecimal[] bigDecimals = number1.divideAndRemainder(number2);
                // 数组的第一个值为商，第二个值为余数
                String discuss = bigDecimals[0].toString();
                String remainder = bigDecimals[1].toString();

                //如果直接被整除说明刚好满足当前最大单位
                if ("0".equals(remainder)) {
                    moreUnit = moreUnit + discuss + sysAuxiliaryUnitDetail.getUnitName();
                    break;
                } else {
                    if ("0".equals(discuss)) {
                        continue;
                    }
                    //没有被整除
                    moreUnit = moreUnit + discuss + sysAuxiliaryUnitDetail.getUnitName();
                    //修改num的值为当前的余数
                    num = remainder;
                    if (sysAuxiliaryUnitDetail == list.get(list.size() - 1)) {
                        moreUnit = moreUnit + remainder + unitByCode.getUnitName();
                    }
                }
            }
        }

        if ("".equals(moreUnit)) {
            moreUnit = materialTotal + "" + unitByCode.getUnitName();
        }
        return moreUnit;

    }
}
